import 'dart:async';
import 'package:flutter/material.dart';

/// 跑马灯组件
/// 支持垂直滚动显示多条文本信息
class DnpMarqueeWidget extends StatefulWidget {
  /// 要显示的文本列表
  final List<String> messages;

  /// 每条消息停留时间（秒）
  final int duration;

  /// 动画过渡时间（毫秒）
  final int animationDuration;

  /// 文本样式
  final TextStyle? textStyle;

  /// 背景颜色
  final Color? backgroundColor;

  /// 内边距
  final EdgeInsetsGeometry? padding;

  /// 高度
  final double? height;

  /// 对齐方式
  final AlignmentGeometry alignment;

  const DnpMarqueeWidget({
    super.key,
    required this.messages,
    this.duration = 3,
    this.animationDuration = 500,
    this.textStyle,
    this.backgroundColor,
    this.padding,
    this.height,
    this.alignment = Alignment.centerLeft,
  });

  @override
  State<DnpMarqueeWidget> createState() => _DnpMarqueeWidgetState();
}

class _DnpMarqueeWidgetState extends State<DnpMarqueeWidget> {
  int _currentIndex = 0;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _startTimer();
  }

  @override
  void didUpdateWidget(DnpMarqueeWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 当消息列表发生变化时，重新启动定时器
    if (oldWidget.messages != widget.messages) {
      _timer?.cancel();
      _currentIndex = 0;
      _startTimer();
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _startTimer() {
    if (widget.messages.isEmpty || widget.messages.length <= 1) {
      return;
    }

    _timer = Timer.periodic(Duration(seconds: widget.duration), (timer) {
      if (mounted) {
        setState(() {
          _currentIndex = (_currentIndex + 1) % widget.messages.length;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (widget.messages.isEmpty) {
      return const SizedBox.shrink();
    }

    return Container(
      height: widget.height,
      padding: widget.padding,
      decoration: BoxDecoration(
        color: widget.backgroundColor,
      ),
      child: ClipRect(
        child: AnimatedSwitcher(
        duration: Duration(milliseconds: widget.animationDuration),
        transitionBuilder: (Widget child, Animation<double> animation) {
          return SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(0, 1),
              end: Offset.zero,
            ).animate(animation),
            child: FadeTransition(
              opacity: animation,
              child: child,
            ),
          );
        },
        child: Align(
          key: ValueKey<int>(_currentIndex),
          alignment: widget.alignment,
          child: Text(
            widget.messages[_currentIndex],
            style: widget.textStyle ??
                const TextStyle(fontSize: 14, color: Colors.black),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        ),
      ),
    );
  }
}
